<?php

class Database
{
	private static $dbh;
	private static $isTransaction;
	
	// return references
	public static function &connection()
	{
		$config = PhormConfig::getConfig();

		if($config->databaseType == 'couchdb')
		{
			$options = array('database' => $config->databaseName,
							 'port'     => $config->databasePort,
							 'host'     => $config->databaseHost);

			self::$dbh = new CouchDB($options);
		}
		else
		{
			if(self::$isTransaction == 0){
				self::$dbh = new PDO($config->databaseType.':host='.$config->databaseHost.';dbname='.$config->databaseName, $config->databaseUsername, $config->databasePassword);
			}
		}
		
		return self::$dbh;
	}
	
	public static function &persistentConnection()
	{
		$config = PhormConfig::getConfig();
		if(self::$isTransaction == 0)
			self::$dbh = new PDO($config->databaseType.':host='.$config->databaseHost.';dbname='.$config->databaseName, $config->databaseUsername, $config->databasePassword,array(PDO::ATTR_PERSISTENT => true));
		return self::$dbh;
	}

	public static function &transactionConnection()
	{
		$config = PhormConfig::getConfig();
		self::$dbh = new PDO($config->databaseType.':host='.$config->databaseHost.';dbname='.$config->databaseName, $config->databaseUsername, $config->databasePassword, array(PDO::ATTR_PERSISTENT => true));
		self::$dbh->beginTransaction();
		self::$isTransaction = 1;
		return self::$dbh;
	}
	
	public static function finish()
	{
		if(self::$isTransaction == 0)
		{
			self::$dbh = null;
		}
	}
	
	public static function commit()
	{
		try
		{
			self::$dbh->commit();
		}
		catch (Exception $e)
		{
			try
			{
				self::$dbh->rollback();
			}
			catch (PDOException $p) {/* there was no transaction present, move on */}
		}
		self::$isTransaction = 0;
		self::finish();
	}

	public static function rollback()
	{
		self::$dbh->rollback();
		self::$isTransaction = 0;
		self::finish();
	}
}
?>
